// 提供复用逻辑的函数（钩子）
import { useIntersectionObserver } from '@vueuse/core'
import { ref, onUnmounted } from 'vue'
import dayjs from 'dayjs'
import { useIntervalFn } from '@vueuse/shared'

// 数据懒加载函数
// apiFn: API函数
export const useLazyData = (apiFn) => {
  const target = ref(null) // 获取DOM
  const result = ref([])
  const { stop } = useIntersectionObserver(
    target,
    // isIntersecting 是否进入可视区域，true是进入 false是移出
    // observerElement 被观察的dom
    ([{ isIntersecting }]) => {
      // 在此处可根据isIntersecting来判断，然后做业务
      if (isIntersecting) {
        stop()
        apiFn().then(data => {
          result.value = data.result
        })
      }
    },
    {
      threshold: 0
    }
  )
  return {
    result,
    target
  }
}

// 倒计时函数封装
export const usePayTime = () => {
  // 倒计时
  const time = ref(0)
  const timeText = ref('')
  const { pause, resume } = useIntervalFn(() => {
    time.value--
    timeText.value = dayjs.unix(time.value).format('mm分ss妙')
    if (time.value <= 0) {
      pause()
    }
  }, 1000, false)

  const start = (countdown) => {
    time.value = countdown
    timeText.value = dayjs.unix(time.value).format('mm分ss妙')
    resume()
  }

  onUnmounted(() => {
    pause()
  })

  return {
    start,
    timeText
  }
}
